package com.data.mall.utils;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component("dynamicBeanManager")
public class DynamicBeanManager implements ApplicationContextAware {
    @Getter
    private static ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        DynamicBeanManager.applicationContext = applicationContext;
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }


    public static <T> T getBean(String name, Class<T> tClass) {
        return (T) applicationContext.getBean(name);
    }


    public static <T> T getBean(Class<T> var1) {
        if (applicationContext == null) return null;
        return applicationContext.getBean(var1);
    }

    public static <T> Map<String, T> beansOfType(Class<T> tClass) {
        return BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, tClass, false, false);
    }
}